package com.mobilesales.android.adapters;

import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.mobilesales.android.R;
import com.mobilesales.android.model.clients.Client;
import com.mobilesales.android.model.orders.OrderItem;

public class OrderItemAdapter extends ArrayAdapter<OrderItem> {

	private Client client;

	public OrderItemAdapter(Context context, int textViewResourceId,
			List<OrderItem> objects) {
		super(context, textViewResourceId, objects);
	}

	public void setClient(Client cli) {
		this.client = cli;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
					"layout_inflater");
			v = vi.inflate(R.layout.order_item_list_item, null);
		}

		OrderItem orderItem = null;
		if ((position >= 0) && (position < this.getCount())) {
			orderItem = this.getItem(position);
		}

		if (orderItem != null) {
			TextView productNameField = (TextView) v
					.findViewById(R.id.productNameTxt);
			TextView productSkuField = (TextView) v
					.findViewById(R.id.productSkuTxt);
			TextView productQuantityField = (TextView) v
					.findViewById(R.id.productQuantityTxt);
			TextView productPriceField = (TextView) v
					.findViewById(R.id.productPriceTxt);

			double price = orderItem.Product.Price
					* (1 + orderItem.Product.Spread)
					* (1 + orderItem.Product.Tax.Value);
			if (this.client != null)
				price *= (1 - client.Group.Discount);

			productNameField.setText(orderItem.Product.Name);
			productSkuField.setText(orderItem.Product.Sku);
			String productQuantityStr = String.format("%s x %s",
					String.format("%1$,.3f", orderItem.Quantity),
					String.format("%1$,.2f", price));
			productQuantityField.setText(productQuantityStr);
			productPriceField.setText(String.format("%1$,.2f", price
					* orderItem.Quantity));
			

		}
		return v;
	}

	@Override
	public void add(OrderItem item) {
		for(int i=0; i< this.getCount(); i++) {
			OrderItem el = this.getItem(i);
			if (el.Product.Id == item.Product.Id) {
				item.Quantity += el.Quantity;
				this.remove(el);
				this.insert(item, i);
				return;
			}
		}
		super.add(item);
	}
	
	@SuppressWarnings("unused")
	private void openEditPopup(final int position) {
		final OrderItem item = this.getItem(position);
		if (item==null) return;
		
	    try {
	        LayoutInflater inflater = (LayoutInflater) this.getContext()
	                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        
	        final View layout = inflater.inflate(R.layout.order_item_edit,null);
	        layout.setBackgroundColor(0xbb000000);
	        final PopupWindow pw = new PopupWindow(layout, 320, 120, true);
	        pw.showAtLocation(layout, Gravity.BOTTOM, 5, 0);
	 
	        Button saveBtn = (Button)layout.findViewById(R.id.saveBtn);
	        Button deleteBtn = (Button)layout.findViewById(R.id.deleteBtn);
	        Button cancelBtn = (Button)layout.findViewById(R.id.cancelBtn);
	        final EditText quantityTxt = (EditText)layout.findViewById(R.id.quantityTxt);
	        
	        quantityTxt.setText(String.format("%1$,.3f", item.Quantity));
	        
	        cancelBtn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					pw.dismiss();
				}
			});
	        
	        saveBtn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					try {
						double newQuantity = Double.parseDouble(quantityTxt.getText().toString());
						remove(item);
						item.Quantity = newQuantity;
						insert(item,position);
						notifyDataSetChanged();
						pw.dismiss();
					}
					catch(Exception ex) {
						quantityTxt.setError(getContext().getString(R.string.ErrorInvalidValue));
					}
					
				}
			});
	        
	       deleteBtn.setOnClickListener(new OnClickListener() {
			
				public void onClick(View v) {
					remove(item);
					notifyDataSetChanged();
					pw.dismiss();
				}
	       });
	    } catch (Exception e) {
	        Log.e("openEditPopup", e.getMessage(), e);
	    }
	}

	public int getPosition(int orderItemId) {
		for (int i = 0; i < this.getCount(); i++) {
			if (this.getItem(i).Id == orderItemId)
				return i;
		}
		return -1;
	}
}
